﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Weixin.Utils
{
    public class IPHelper
    {
        /// <summary>
        /// 获取客户机的ＩＰ
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            string ip = "";
            if (System.Web.HttpContext.Current != null)
            {
                System.Web.HttpRequest Request = System.Web.HttpContext.Current.Request;
                System.Web.HttpServerUtility Server = System.Web.HttpContext.Current.Server;

                string addr = "";
                try
                {
                    /*穿过代理服务器取远程用户真实IP地址：*/
                    if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                    {
                        addr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                    }
                    else
                    {
                        addr = Request.ServerVariables["REMOTE_ADDR"].ToString();
                    }
                }
                catch
                {
                    addr = Request.UserHostAddress;
                }

                if (addr == null)
                {
                    addr = "";
                }

                ip = addr.Split(',')[0];
            }
            return ip;
        }

        /// <summary>
        /// 计算Ip地址的整数值
        /// </summary>
        /// <param name="strIp">Ip地址</param>
        /// <returns>返回类型为ulong的长整数值</returns>
        public static long ComputeIpValue(string strIp)
        {
            string[] ipVals = strIp.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            long rst = long.Parse(ipVals[3]);
            rst += long.Parse(ipVals[2]) * 256;
            rst += long.Parse(ipVals[1]) * 256 * 256;
            rst += long.Parse(ipVals[0]) * 256 * 256 * 256;
            return rst;
        }
    }
}
